//
//  订单支付Ctr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/14.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp
// import mosdks

public typealias GoodsOrderPayCtr = PayController

public enum MallPayTask{
    case oneGoods
    case cart
    case groups
    public var type:String{
        switch self {
        case .groups:
            return "groups"
        default:
            return "order"
        }
    }
}

public class PayController: ListController {
    
    
    
    public var task:MallPayTask = .oneGoods
    var sections:TP.section{
        get{
            var sec:TP.section = TP.section()
            switch payStatus {
            case .waiting:
                
                var dispathSc = [[String:Any]]()
                let discount_price = mo.detail[float:"discount_price",0]
                if discount_price > 0{
                    dispathSc.append([
                        "cellID":"discount",
                        "__model":mo.detail
                        ])
                }
                let orderObj = DataNode.path(node: "order", mo.detail, value: NSMutableDictionary())
                var seller_ = ["cellID":"seller","__model":mo.detail] as [String : Any]
                if(task == .cart){
                    seller_ =  ["id":"blank1"]
                }
            
                sec = [
                    [
                        ["id":"blank"],
                        ["id":"orderNo","orderNo":orderObj.possible("ordersn","orderno", default: "")],
                        ["id":"blank"],
                        [
                            "title":"选择支付方式".loc,
                            "cellID":"payMethod",
                            FK.fields:[
                                [
                                    FK.value:PayMethod.defaultMethod.rawValue,
                                    FK.options:PayMethod.payOptions,
                                    FK.field:StrField(id: "paytype", defaultV: nil, need: true, hiden: false, rule:
                                        JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "选择支付方式".loc, err_msg: "选择支付方式".loc))
                                ]
                            ],
                        ],
                        seller_,
                        [
                            "cellID":"goods",
                            "options":DataNode.path(node: "goods",orderObj, value: NSMutableArray()),
                            ],
                        ],
                    [
                        ["id":"price","__model":orderObj],
                        ["id":"blank"],
                        ["id":"blank"],
                        ],
                    [
                    ]
                ]
                
            case .success:
                sec = [
                    [
                        ["cellID":"success"],
                        [
                            "cellID":"recommend",
                            "options":[
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods1"],
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods2"],
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods3"]
                            ]
                        ]
                    ]
                ]
            case .failed:
                sec = [
                    [
                        ["cellID":"failed"],
                        //                        ["cellID":"seller","logo":__logos.one_str,"name":__seller.one_str,"info":__titles.creat_info(5)],
                        [
                            "cellID":"recommend",
                            "options":[
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods1"],
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods2"],
                                //                                ["img":__goods.one_str,"title":__goodsNames.one_str,"name":"goods3"],
                            ]
                        ]
                    ]
                ]
                
            }
            
            return sec
            
            
        }
    }
    
    let selector:TP.selector = [
        "id<blank1>":BlankLine<line.px1>.self,
        "id<blank>":BlankLine<line.px10>.self,
        "id<orderNo>":NoCell.self,
        "id<price>":PriceCell.self,
        "cellID<payMethod>":PayCell<PayKit>.self,
        "cellID<goods>":GoodsCell.self,
        "cellID<success>":SuccessCell.self,
        "cellID<failed>":FailedCell.self,
        
        "cellID<discount>":SCOrderSubmitCtr.DiscountInfoCell.self,
        "cellID<seller>":ShoppingCartListCtr.SellerCell1.self,
        "cellID<recommend>":GoodsRecCell.self,
        ]
    
    
    var orderID:String{
        get{
            var id = mo.model["order.id",""]
            if id.len < 1
            {
                id = mo.model["product_id",""]
            }
            if id.len < 1
            {
                id = mo.model["id",""]
            }
            if id.len < 1
            {
                id = mo.model["orderid",""]
            }
            
            return id
        }
    }

    
    var detailURL:String{
        switch task {
        case .groups:
            return _SURL.团购订单详情.url
        default:
            return _SURL.订单详情.url

        }
    }
    
    override public func mo_request_send() {
        weak var wself = self
//        if(from=="goods"){
            loadingV.loading()
        var ps:[String:Any] = ["orderid":orderID]
      
        JoTask().get.params(ps).url(detailURL).log_response().log.json_handle { (status, msg, obj, resp) in
                wself?.loadingV.dismiss()
                if status.isSuccess{
                    if let dict = obj as? NSMutableDictionary{
                        wself?.mo.detail = dict
                        return
                    }
                }
                wself?.mo_request_alert()
            }.run()
//        }else if(from=="cart"){
//            loadingV.loading()
//            JoTask().get.params(["orderid":self.orderID,"type":type])._surl(.订单支付v2_1).log.log_response().json_handle { (status, msg, obj, resp) in
//                wself?.loadingV.dismiss()
//                if status.isSuccess{
//                    if let dict = obj as? NSMutableDictionary{
//                        return
//                    }
//                }
//                wself?.mo_request_alert()
//            }.run()
//        }
    }
    
    override public func mo_detail_reload() {
        self.loadSection()
        //        tableView.load(sections: sections, selector: selector)
        //        tableView.reloadData()
    }
    
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        //        tableView.load(sections: sections, selector: selector)
        tableView.buildDynamicHeight(height: 200)
        tableView.separatorStyle = .none
        self.title = "订单支付".loc
        tableView.backgroundColor = ._tableBackground
        //        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "toggle", style: .plain, target: self, action: #selector(toggle))
        
        
        self.mo_request_send()
        
    }
    
    
    
    
    var payStatus:PayStatus = .waiting
    
    //    @objc func toggle()
    //    {
    //        paySuccessed = !paySuccessed
    //        self.mo_request_load(obj: 0)
    //    }
    
    func refreshRecommend() {
        weak var wself = self
        //        loadingV.loading()
        JoTask().get._surl(.商品推荐).json_handle { (status, msg, obj, resp) in
            //            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let ws = wself{
                    if let goods = obj as? NSMutableArray
                    {
                        //                    let brand = DataNode.path(node: "brand", obj,value:NSMutableDictionary())
                        let sec = IndexSet(integer:0)
                        //                    ws.tableView.model <-- ("section0.1.seller",brand,NodeInsert.dictValue)
                        ws.tableView.model <-- ("section0.1.options",goods,NodeInsert.arrayRefresh)
                        ws.tableView.reloadSections(sec, with: .fade)
                    }
                }
            }
            }.run()
    }
    
    func loadSection(){
        
        switch self.payStatus {
        case .failed,.success:
            self.bottomBar.actionBar = __Line0()
        case .waiting:
            let payBar = PayBar()
            payBar.controller = self
            payBar.mo.model = self.mo.detail
            weak var wself = self
            payBar.confirmPayAction = {
                wself?.beginPay()
            }
            self.bottomBar.actionBar = payBar
        }
        
        tableView.layoutIfNeeded()
        tableView.load(sections: sections, selector: selector)
        tableView.reloadData()
        switch self.payStatus {
        case .failed,.success:
            refreshRecommend()
        case .waiting:
            break
        }
        
    }
    
    
    func beginPay() {
        
        let info = JoPaw.paw(tableView: tableView)
        if info.validate{
            var params = info.values
//            params["orderid"] = self.orderID
            params["id"] = self.orderID

            let pay_method = PayMethod.method(with: params.mutable_dictionary["paytype",""])
            
            weak var wself = self
            HUD.share.show().mode(.indeterminate)
            var signNode = "wechat"
            
            let taskId = "\(orderID)|\(task.type)"
            let taskType = task.type

            JoTask().get.params(["orderid":self.orderID,"type":taskType])._surl(.订单支付v2_1).log.log_response().json_handle { (status, msg, obj, resp) in
                HUD.share.hide(animated: true)
                if status.isSuccess{
                    if let dict = obj as? NSMutableDictionary{
                        
                        let paySgin = dict.get(node: "payinfo.\(pay_method.signNode)", defaultV: NSMutableDictionary())
//                        if payMethod = "wechat"
//                        print("_____IIIIS--",taskId,paySgin,pay_method)

                        DoPay.pay(pay_method.rawValue, pay_id: taskId, task_type:taskType, paySgin, finish_block: { (result, task_type, pay_id) in
                            switch result{
                            case .ok:
                                wself?.payStatus = .success
                                wself?.loadSection()
                                __post(notify: Goods.Notice.goodsOrderChange)
                            case .canle:
                                break
                            case .failed(_,_):
                                wself?.payStatus = .failed
                                wself?.loadSection()
                            }
                        })
                        
                        return
                    }
                }
                msg.alert()
                }.run()
        }
        
    }
    
    let bottomBar = BottomView()
    override public func layTable(tableView: UIView) {
        //        super.layTable(tableView: tableView)
        jo_contentView.eelay = [
            [tableView,[ee.T.L.R],[bottomBar,ee.T,ee.B]],
            [bottomBar,[ee.L.B.R]],
        ]
    }
    
    override public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case "rePay":
            self.payStatus = .waiting
            loadSection()
        case "seeOrder":
            switch task {
            case .groups:
                let ctr = GroupOrderListCtr()
                self.navigationController?.pushViewController(ctr, animated: true)
            default:
                let ctr = GoodsOrderListCtr()
                self.navigationController?.pushViewController(ctr, animated: true)
            }
           
//            self.navigationController?.popViewController(animated: true)
        default:
            break
        }
    }
}

//待支付
extension PayController{
    class __Line0:JoView{
        override var intrinsicContentSize: CGSize{
            return [Swidth,0]
        }
    }
    class BottomView:JoView{
        var cons = [NSLayoutConstraint]()
        var actionBar:UIView = __Line0()
        {
            didSet{
                oldValue.removeFromSuperview()
                self.removeConstraints(cons)
                self.cons = setEeLays(lays: [
                    [actionBar,[ee.T.L.B.R]]
                    ]).1
                actionBar.layoutIfNeeded()
                self.layoutIfNeeded()
                self.superview?.layoutIfNeeded()
            }
        }
    }
    
    class PayBar:EeBottomBar{
        
        var confirmPayAction:()->Void = {}
        //        override func addLayoutRules() {
        //            let line = UIView()
        //            contentView.eelay = [
        //                [line,[ee.T.L.R],"0.5"],
        //                [confirmBt,[ee.Y.R,[0,-AppTheme.edge]]],
        //                [priceL,[confirmBt,ee.L,ee.R,-30],[ee.Y]],
        //            ]
        //            line.backgroundColor = UIColor.separator_color
        //            _ = confirmBt.ui.buttonColor(hex: UIColor.main_hex).ncolor(hex: "#fff").font(size: 14).ntitle(title: "确认支付").corner4
        //            confirmBt.contentEdgeInsets = [8,16]
        //            confirmBt.addTarget(self, action: #selector(confirmPay), for: .touchUpInside)
        //            priceL.attributedText = "合计：".ui.font16.color(hex: "#111").astring + "¥\(0)".ui.color(hex: UIColor.main_hex).font16.astring
        //        }
        
        let priceL = UILabel()
        let confirmBt = UIButton()
        
        override func addLayoutRules() {
            let line = UIView()
            contentView.eelay = [
                [confirmBt,[ee.T.B.R],150],
                [priceL,[confirmBt,ee.L,ee.R,-30],[ee.L,AppTheme.edge.+1000],[ee.Y]],
                [line,[ee.T.L.R],"\(TP.separatorHeight)"],
            ]
            contentView.setContentConstrainToHighLever()
            line.backgroundColor = ._separator
            _ = confirmBt.ui.ncolor(hex: "#fff").font(size: 14).ntitle(title: "确定支付".loc)
            //            confirmBt.contentEdgeInsets = [8,16]
            confirmBt.setBackgroundImage(UIImage(named: "shop_buy"), for: .normal)
            priceL.attributedText = "\("合计".loc)：".ui.font16.color(color: ._foreground).astring + "¥\(0)".ui.color(color: ._tint).font16.astring
            confirmBt.addTarget(self, action: #selector(confirmPay), for: .touchUpInside)
        }
        
        override func mo_model_reload() {
            
            let price = mo.model[float:"order.price",0]
            priceL.attributedText = "\("合计".loc)：".ui.font16.color(color: ._foreground).astring + "¥\(price.price_display)".ui.color(color: ___shop.tint).font16.astring
            
        }
        
        
        @objc func confirmPay(){
            self.confirmPayAction()
        }
        
        
        override var contentHeight: CGFloat{
            return 45
        }
    }
    class NoCell:JoTableCell{
        let noL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [noL,[ee.T.L.B.R,[16,AppTheme.edge,-16,-AppTheme.edge]]],
            ]
        }
        override func mo_model_reload() {
            noL.attributedText = "\("订单编号".loc)：".ui.color(color: .color(light: "#222", dark: "#f1f1f1")).font14.astring + mo.model.possible("orderNo","orderno", default: "").ui.color(color: ._foreground).font14.astring
        }
    }
    
    
    class PriceCell: JoTableCell {
        
        class ItemView: RuleCell {
            let nameL = UILabel()
            let priceL = UILabel()
            override func addLayoutRules() {
                contentView.eelay = [
                    [nameL,[ee.L.Y]],
                    [priceL,[ee.R.Y]],
                ]
                
                nameL.ui.font12.text(color: ._weak).text("")
                priceL.ui.font12.text(color: ._weak).right.text("¥ 120")
                
            }
            override func mo_model_reload() {
                nameL.text = mo.model["name",""]
                priceL.text =  "¥ " + mo.model["value",""]
                
            }
        }
        
        let listV = GoodsListView<ItemView>()
        override func addLayoutRules() {
            contentView.eelay = [
                [listV,[ee.X],[ee.T],[ee.B]],
            ]
            
        }
        override func mo_model_reload() {
            listV.listV.item_height = 26
            listV.listV.space = (0,0)
            listV.listV.padding = [4,0]
            listV.listV.options_node = "__model.orderprice"
            listV.mo.model = mo.model
            
        }
    }
    
    
    class GoodsCell: JoTableCell {
        class GoodsView: RuleCell {
            let imgV = UIImageView()
            let titleL = UILabel()
            let tagsL = UILabel()
            let priceL = UILabel()
            let numL = UILabel()
            override func addLayoutRules() {
                let __line = UIView()
                
                contentView.eelay = [
                    [imgV,[ee.Y.L],"64",64],
                    [titleL,[imgV,ee.R,ee.L,8],[imgV,ee.T],[priceL,ee.L,ee.R,-8]],
                    [tagsL,[imgV,ee.R,ee.L,8],[imgV,ee.B],[numL,ee.L,ee.R,-8]],
                    [priceL,[ee.R,0.+1000],[titleL,ee.Y]],
                    [numL,[ee.R],[tagsL,ee.B]],
                    [__line,[ee.L.B.R,[-AppTheme.edge,0,AppTheme.edge]],"\(TP.separatorHeight)"]
                ]
                __line.backgroundColor = ._separator
                
                //                imgV.img_url = __goods.one_str
                imgV.ui.holder(type: .grayBack)
                titleL.ui.font14.text(color: ._foreground).text(__goodsNames.one_str)
                tagsL.ui.font13.text(color: ._foreground).text("颜色：黑")
                priceL.ui.font13.text(color: ___shop.second).right.text("¥ 120")
                numL.ui.font13.text(color: ._weak).right.text("X1")
                titleL.setContentConstrainToLowLever()
            }
            override func mo_model_reload() {
                titleL.text = mo.model["title",""]
                tagsL.text = mo.model["optiontitle",""]
                imgV.img_url = mo.model["thumb",""]
                numL.text = "X " + mo.model["total","0"]
                
                let price = mo.model[float:"price",0]
                priceL.text = "¥ \(price.price_display)"
                
            }
        }
        
        let goodsV = GoodsListView<GoodsView>()
        override func addLayoutRules() {
            contentView.eelay = [
                [goodsV,[ee.X],[ee.T],[ee.B]],
            ]
        }
        
        override func mo_model_reload() {
            goodsV.listV.item_height = 94
            goodsV.listV.space = (0,0)
            goodsV.mo.model = mo.model
            
        }
    }
    
    
    class GoodsRecCell:JoTableCell{
        class RecKit:RuleCell{
                let imgV = UIImageView()
                let titleL = UILabel()
                let priceL = UILabel()
                
            override func addLayoutRules() {
                contentView.eelay =
                    [
                        [imgV,[ee.T.L.R],[ee.width,ee.height]],
                        [titleL,[imgV,ee.B,ee.T,4],[ee.L.R]],
                        [priceL,[ee.B,-4],[ee.L.R]
                    ]
                ]
                _ = priceL.ui.text(color: ._weak).center.font12
                _ = titleL.ui.text(color: ._foreground).center.font12
                imgV.ui.holder(type: .image(.goods_holder)).set(radius: 0, width: 0.4, color: .color(light: "#ccc9", dark: "#aaa2"))
            }
            override func mo_model_reload() {
            
                
                imgV.img_url = mo.model["thumb",""]
                imgV.backgroundColor = ._cellBackground
                titleL.attributedText = mo.model.possible("title","subtitle", default: "").ui.font10.cl_666.lineSpace(6).astring
                priceL.attributedText = "\("¥".loc) \(mo.model[float:"marketprice",0].price_display)".ui.font10.color(color: ___shop.second).astring
                titleL.numberOfLines = 1
                priceL.numberOfLines = 1
            }
        }
        
        let listV = RuleView<RecKit>.init()
        override func addLayoutRules() {
            contentView.eelay = [
                [listV,[ee.T.L.B.R]]
            ]
            
            let w = (Swidth - 2*AppTheme.edge)/3.0
            //            contentView.addSubviews(listV)
            listV.space = (8,8)
            listV.limit_width = Swidth
            listV.padding = [10,AppTheme.edge,10,AppTheme.edge]
            listV.que_num = 3
            listV.item_height = w + 38.0
            
            weak var wself = self
            listV.touchAction = { _,_,data in
                Goods.seeDetail(obj: data, at: wself?.content_controller)
            }
        }
        //    func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
        //        let ctr = GoodsDetailCtr()
        //        ctr.mo.model = data
        //        content_controller?.navigationController?.pushViewController(ctr, animated: true)
        //    }
        
        override func mo_model_reload() {
            listV.mo.model = mo.model
        }
    }
}


//支付成功
extension PayController{
    class SuccessCell:JoTableCell{
        let infoL = UILabel()
        let iconV = UIImageView()
        let seeOrderBt = UIButton()
        override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            iconV.image = UIImage(named: "me_yycg")?.dynamicImage(color: ._foreground)
        }
        override func addLayoutRules() {
            contentView.eelay = [
                [infoL,[ee.T.X,[36.+1000,10.+1000]],[ee.L,.>40],[ee.R,.<(-30)]],
                [iconV,[infoL,ee.T,-1],[infoL,ee.L,ee.R,-6],"18",18],
                [seeOrderBt,[infoL,ee.B,ee.T,20],[ee.X],[ee.B,-36]],
            ]
            
            iconV.image = UIImage(named: "me_yycg")?.dynamicImage(color: ._foreground)
            _ = infoL.ui.line(0)
            "查看我的[XX]".replaceVars(values: OrderScheme.default.name)
            seeOrderBt.ui.font(size: 14).ncolor(color: ___shop.tint).ntitle(title: "查看我的[XX]".replaceVars(values: OrderScheme.default.name)).set(radius: 4, width: 1, color: ___shop.tint)
            seeOrderBt.contentEdgeInsets = [6,17]
            contentView.backgroundColor = ._background
            seeOrderBt.addTarget(self, action: #selector(seeOrder), for: .touchUpInside)
            
            infoL.attributedText = "付款成功".loc.ui.center.font16.color(color: ._foreground).lineSpace(6).astring
        }
        @objc func seeOrder() {
            active(ID: "seeOrder")
        }
        
    }
    
    class FailedCell:JoTableCell{
        override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            iconV.image = UIImage(named: "me_yysb")?.dynamicImage(color: ._foreground)

        }
        let infoL = UILabel()
        let iconV = UIImageView()
        let seeOrderBt = UIButton()
        override func addLayoutRules() {
            contentView.eelay = [
                [infoL,[ee.T.X,[36.+1000,(20).+1000]],[ee.L,.>50],[ee.R,.<(-30)]],
                [iconV,[infoL,ee.T,-1],[infoL,ee.L,ee.R,-6],"18",18],
                [seeOrderBt,[infoL,ee.B,ee.T,20],[ee.X],[ee.B,-36]],
            ]
            
            iconV.image = UIImage(named: "me_yysb")?.dynamicImage(color: ._foreground)
            _ = infoL.ui.line(0)
            seeOrderBt.ui.font(size: 14).ncolor(color: ___shop.tint).ntitle(title: "点击重新付款".loc).set(radius: 4, width: 1, color: ___shop.tint)
            seeOrderBt.contentEdgeInsets = [6,17]
            contentView.backgroundColor = ._background
            
            infoL.attributedText = "抱歉支付失败！".loc.ui.center.font16.color(color: ._foreground).lineSpace(6).astring
            seeOrderBt.addTarget(self, action: #selector(rePay), for: .touchUpInside)
        }
        @objc func rePay() {
            active(ID: "rePay")
        }
    }
    
    class SellerCell: JoTableCell {
        let logoV = UIImageView()
        let nameL = UILabel()
        let infoL = UILabel()
        
        override func addLayoutRules() {
            let bt = UIButton()
            contentView.eelay = [
                [logoV,[ee.T.L.B,[20,AppTheme.edge,-4]],"52",52],
                [nameL,[logoV,ee.R,ee.L,8],[ee.R,-AppTheme.edge],[logoV,ee.T],"16"],
                [infoL,[logoV,ee.R,ee.L,8],[ee.R,-AppTheme.edge],[logoV,ee.B],"32"],
                [bt,[ee.T.L.B.R]],
            ]
            logoV.bsui.set(radius: 0, width: 0.5, color: .color(light: "#ddd", dark: "#ccc2"))
            _ = nameL.ui.font15.cl_222
            _ = infoL.ui.font12.cl_444.line(2)
            
            bt.addTarget(self, action: #selector(openSeller), for: .touchUpInside)
        }
        @objc func openSeller(){
//            let ctr = SellerHomeCtr()
//            ctr.mo.model = DataNode.path(node: "seller", mo.model, value: NSMutableDictionary())
            let obj = DataNode.path(node: "seller", mo.model, value: NSMutableDictionary())
            Goods.seeSeller(obj: obj, at: mo.controller)
//            content_controller?.navigationController?.pushViewController(ctr, animated: true)
        }
        override func mo_model_reload() {
            logoV.img_url = mo.model["seller.thumb",""]
            nameL.text = mo.model["seller.brand_name",""]
            infoL.text = mo.model["seller.desc",""]
        }
        
    }
    
    
}

